<template>
  <div class="register-container">
    <!-- 返回首页 -->
    <div class="back-home">
      <el-button link @click="goToHome">← 返回首页</el-button>
    </div>

    <el-card class="register-card">
      <template #header>
        <div class="card-header">注册无爱咖啡</div>
      </template>

      <el-form ref="formRef" :model="registerForm" :rules="rules" class="register-form">
        <!-- 邮箱 -->
        <el-form-item class="custom-form-item" prop="email">
          <el-input
            v-model="registerForm.email"
            placeholder="请输入QQ邮箱"
            class="custom-input"
          ></el-input>
        </el-form-item>

        <!-- 手机号 -->
        <el-form-item class="custom-form-item" prop="phone">
          <el-input
            v-model="registerForm.phone"
            placeholder="请输入手机号"
            class="custom-input"
          ></el-input>
        </el-form-item>

        <!-- 用户名 -->
        <el-form-item class="custom-form-item" prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名"
            class="custom-input"
          ></el-input>
        </el-form-item>

        <!-- 密码 -->
        <el-form-item class="custom-form-item" prop="password">
          <el-input
            type="password"
            v-model="registerForm.password"
            placeholder="请输入密码"
            show-password
            class="custom-input"
          ></el-input>
        </el-form-item>

        <!-- 确认密码 -->
        <el-form-item class="custom-form-item" prop="confirmPassword">
          <el-input
            type="password"
            v-model="registerForm.confirmPassword"
            placeholder="请再次输入密码"
            show-password
            class="custom-input"
          ></el-input>
        </el-form-item>

        <!-- 验证码 -->
        <el-form-item class="custom-form-item">
          <el-row :gutter="10" justify="center">
            <el-col :span="15">
              <el-input
                v-model="registerForm.code"
                placeholder="请输入验证码"
                class="custom-input"
              ></el-input>
            </el-col>
            <el-col :span="9">
              <el-button
                type="primary"
                @click="getCode"
                :disabled="isGettingCode"
                plain
                class="code-button"
              >
                {{ codeButtonText }}
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item class="custom-form-item">
          <el-button
            type="primary"
            @click="submitRegister"
            class="register-button"
          >
            注册
          </el-button>
        </el-form-item>
      </el-form>
      <!-- 返回首页按钮 -->
      <div class="back-home">
        <el-button link @click="goToHome">
          ← 返回首页
        </el-button>
      </div>
      <!-- 已有账号 -->
      <div class="login-link">
        <span>已有账号？</span>
        <!-- <el-button link @click="goToLogin">点我登录</el-button> -->
        <span class="login-text" @click="goToLogin">点我登录</span>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getCode as sendGetCode, register as sendRegister } from '@/api/register'

const router = useRouter()

// 表单数据
const registerForm = reactive({
  email: '',
  phone: '',
  username: '',
  password: '',
  confirmPassword: '',
  code: ''
})

// 表单验证规则
const rules = {
  email: [
    { required: true, message: '请输入QQ邮箱', trigger: 'blur' },
    { pattern: /^[1-9]\d{4,10}@qq\.com$/, message: '请输入有效的QQ邮箱', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度应在2到20个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应在6到20个字符之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const formRef = ref(null)

// 验证码倒计时逻辑
const isGettingCode = ref(false)
const codeButtonText = ref('获取验证码')
let countdownTimer = null

const getCode = async () => {
  if (!registerForm.email) {
    ElMessage.warning('请先填写邮箱')
    return
  }

  try {
    // 发送请求获取验证码（仅携带邮箱）
    const res = await sendGetCode({ email: registerForm.email })

    if (res.code === 1) {
      startCountdown()
      ElMessage.success('验证码已发送')
    } else {
      ElMessage.error(res.msg || '验证码发送失败')
    }
  } catch (error) {
    ElMessage.error('网络错误，请重试')
    console.error('获取验证码失败:', error)
  }
}
function startCountdown() {
  let count = 60
  isGettingCode.value = true
  codeButtonText.value = `重新发送(${count})`

  countdownTimer = setInterval(() => {
    count--
    if (count <= 0) {
      clearInterval(countdownTimer)
      isGettingCode.value = false
      codeButtonText.value = '获取验证码'
    } else {
      codeButtonText.value = `重新发送(${count})`
    }
  }, 1000)
}
// 提交注册
const submitRegister = async () => {
  // 检查所有字段是否填写
  const { email, phone, username, password, confirmPassword, code } = registerForm

  if (!email || !phone || !username || !password || !confirmPassword || !code) {
    ElMessage.warning('请填写所有字段')
    return
  }

  if (password !== confirmPassword) {
    ElMessage.warning('两次输入的密码不一致')
    return
  }

  try {
    const res = await sendRegister(registerForm)

    if (res.code === 1) {
      ElMessage.success('注册成功！')
      router.push('/me/login')
    } else {
      ElMessage.error(res.msg || '注册失败')
    }
  } catch (error) {
    ElMessage.error('注册失败，请重试')
    console.error('注册失败:', error)
  }
}

// 模拟注册 API
const register = async (data) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({ success: true })
    }, 800)
  })
}

// 页面跳转方法
const goToHome = () => {
  router.push('/')
}

const goToLogin = () => {
  router.push('/me/login')
}
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px;
  box-sizing: border-box;
}

.register-card {
  position: relative;
  width: 100%;
  max-width: 500px;
  padding: 40px;
  border-radius: 16px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
  background-color: #ffffff;
  transition: all 0.3s ease-in-out;
}

.card-header {
  text-align: center;
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 24px;
  color: #2c3e50;
}

.register-form .custom-form-item {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.custom-input {
  width: 100%;
  text-align: center;
  height: 40px;
  font-size: 14px;
}

.code-button {
  width: 100%;
  height: 40px;
}

.register-button {
  width: 100%;
  margin-top: 20px;
  background-color: #5c6bc0;
  color: white;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  padding: 12px 20px;
  transition: background-color 0.3s ease;
}
.register-button:hover {
  background-color: #3949ab;
}
.back-home {
  position: absolute;
  top: 20px;
  left: 40px;
  font-size: 14px;
}

.back-home .el-button {
  padding: 0;
  color: #5c6bc0;
  font-weight: 500;
}

.back-home .el-button:hover {
  color: #3949ab;
}
.login-link {
  display: flex;
  justify-content: center; /* 使内容居中显示 */
  align-items: center; /* 垂直居中 */
  margin-top: 20px;
  text-align: right;
  margin-top: 10px;
  font-size: 14px;
  color: #666;
}
.login-link .span {
   margin-right: 10px; /* 增加 span 和文本之间的间距 */
}
.login-link .span:hover {
  color: #3949ab;
}

.login-text {
  color: #5c6bc0; /* 设置字体颜色为蓝色 */
  cursor: pointer; /* 添加鼠标悬停效果 */
  transition: color 0.3s ease;
}
.back-home {
  position: absolute;
  top: 20px;
  left: 40px;
  font-size: 14px;
}
.back-home .el-button {
  padding: 0;
  color: #5c6bc0;
  font-weight: 500;
}
.back-home .el-button:hover {
  color: #3949ab;
}
</style>